package com.huawei.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.huawei.domain.LoginUser;
import com.huawei.utils.JwtUtil;
import com.huawei.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1.获取请求头中的token信息
        String token = request.getHeader("FairyCatAuthorization");

        //判断token是否存在
        if(StrUtil.isEmpty(token)){
            //如果token是空的 说明不存在 则直接放行让后面的过滤器处理
            filterChain.doFilter(request,response);
            return ;
        }

        //来到此处说明token不为空 则开始解析token 获取userId
        String userId=null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            System.out.println("当前的错误提示~： "+e.getMessage());
        }

        System.out.println("当前用户id："+userId);

        //获取到userId之后 再从Redis中通过userId获取用户信息
        // 修改这部分代码：
        Object cacheObj = redisCache.getCacheObject("javaWeb:user:" + userId);
        LoginUser loginUser = cacheObj instanceof LoginUser ?
                (LoginUser) cacheObj :
                JSON.parseObject(cacheObj.toString(), LoginUser.class);

        if(loginUser == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }


//        LoginUser loginUser = (LoginUser) redisCache.getCacheObject("javaWeb:user:" + userId);
        UsernamePasswordAuthenticationToken upAuthToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());


        SecurityContextHolder.getContext().setAuthentication(upAuthToken);

        filterChain.doFilter(request,response);

    }
}
